package com.java.util;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.HashMap;
import java.util.Properties;

public class AlibabaSMSUtil {

    private final static String accessKeyId;
    private final static String accessKeySecret;
    private final static String signName;
    private final static String regionId;
    private final static String domain;
    private final static String version;
    private final static String action;
    private final static String templateParam;

    static {
        Properties ppt = new Properties();
        try {
            ppt.load(AlibabaSMSUtil.class.getClassLoader().getResourceAsStream("sms.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        accessKeyId = ppt.getProperty("accessKeyId");
        accessKeySecret = ppt.getProperty("AccessKeySecret");
        signName = ppt.getProperty("SignName");
        regionId = ppt.getProperty("RegionId");
        domain = ppt.getProperty("Domain");
        version = ppt.getProperty("Version");
        action = ppt.getProperty("Action");
        templateParam = ppt.getProperty("TemplateParam");
    }

    public static boolean send(String phoneNumber, String code) {
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
                IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(domain);
        request.setVersion(version);
        request.setAction(action);
        request.putQueryParameter("RegionId", regionId);
        request.putQueryParameter("PhoneNumbers", phoneNumber);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", "{\"code\":\"" + code + "\"}");
        request.putQueryParameter("TemplateParam", templateParam);
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            String json = response.getData();
            Gson g = new Gson();
            HashMap result = g.fromJson(json, HashMap.class);
            if ("OK".equals(result.get("Message"))) {
                return true;
            }
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}
